using AutoMapper;
using MediatR;
using RBAC.Domain.MaterialManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.MaterialFile;
using System.Transactions;

namespace RBAC.Write.Api.Application.Handler.ERP.MaterialFile
{
    /// <summary>
    /// 添加物料分类处理类
    /// </summary>
    public class AddMaterTypeHandler : IRequestHandler<AddMaterTypeCommand, APIResult<long>>
    {
        private readonly IBaseRepository<MaterType> materTypeRepository;
        private readonly ILogger<AddMaterTypeHandler> logger;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="materTypeRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public AddMaterTypeHandler(
            IBaseRepository<MaterType> materTypeRepository,
            ILogger<AddMaterTypeHandler> logger,
            IMapper mapper)
        {
            this.materTypeRepository = materTypeRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 处理添加物料分类请求
        /// </summary>
        /// <param name="request">添加物料分类请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        public async Task<APIResult<long>> Handle(AddMaterTypeCommand request, CancellationToken cancellationToken)
        {
            APIResult<long> result = new APIResult<long>();

            try
            {
                logger.LogInformation("开始创建物料分类: {TypeName}", request.TypeName);

                // 1. 数据验证
                if (string.IsNullOrWhiteSpace(request.TypeCode))
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "分类编码不能为空";
                    logger.LogWarning("分类编码验证失败");
                    return result;
                }

                if (string.IsNullOrWhiteSpace(request.TypeName))
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "分类名称不能为空";
                    logger.LogWarning("分类名称验证失败");
                    return result;
                }

                if (request.TypeCode.Length > 50)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "分类编码长度不能超过50个字符";
                    logger.LogWarning("分类编码长度验证失败: {Length}", request.TypeCode.Length);
                    return result;
                }

                if (request.TypeName.Length > 100)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "分类名称长度不能超过100个字符";
                    logger.LogWarning("分类名称长度验证失败: {Length}", request.TypeName.Length);
                    return result;
                }

                // 2. 检查分类编码是否已存在
                var existingByCode = materTypeRepository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM MaterType WHERE TypeCode = @TypeCode AND IsDeleted = false",
                    new { TypeCode = request.TypeCode });

                if (existingByCode > 0)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "分类编码已存在";
                    logger.LogWarning("分类编码已存在: {TypeCode}", request.TypeCode);
                    return result;
                }

                // 3. 检查分类名称是否已存在
                var existingByName = materTypeRepository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM MaterType WHERE TypeName = @TypeName AND IsDeleted = false",
                    new { TypeName = request.TypeName });

                if (existingByName > 0)
                {
                    result.Code = APIEnums.Error;
                    result.Msg = "分类名称已存在";
                    logger.LogWarning("分类名称已存在: {TypeName}", request.TypeName);
                    return result;
                }

                // 4. 验证上级分类是否存在（如果有上级分类）
                if (request.ParentId.HasValue && request.ParentId.Value > 0)
                {
                    var parentExists = materTypeRepository.QueryFirstOrDefault<int>(
                        "SELECT COUNT(1) FROM MaterType WHERE Id = @Id AND IsDeleted = false",
                        new { Id = request.ParentId.Value });

                    if (parentExists == 0)
                    {
                        result.Code = APIEnums.Error;
                        result.Msg = "指定的上级分类不存在";
                        logger.LogWarning("上级分类验证失败: {ParentId}", request.ParentId.Value);
                        return result;
                    }
                }

                // 5. 创建物料分类实体
                var materType = mapper.Map<MaterType>(request);
                materType.CreateTime = DateTime.Now;
                materType.IsDeleted = false;
                materType.CreateUser = "admin"; // 默认管理员用户

                logger.LogInformation("物料分类映射完成: TypeName={TypeName}, ParentId={ParentId}",
                    materType.TypeName, materType.ParentId);

                using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    try
                    {
                        // 6. 保存物料分类信息
                        var sql = @"INSERT INTO MaterType (TypeCode, TypeName, Unit, Status, Lenght, SupplyMode, ParentId, CreateTime, IsDeleted, CreateUser) 
                                   VALUES (@TypeCode, @TypeName, @Unit, @Status, @Lenght, @SupplyMode, @ParentId, @CreateTime, @IsDeleted, @CreateUser);
                                   SELECT LAST_INSERT_ID();";

                        var parameters = new
                        {
                            materType.TypeCode,
                            materType.TypeName,
                            materType.Unit,
                            materType.Status,
                            materType.Lenght,
                            materType.SupplyMode,
                            materType.ParentId,
                            materType.CreateTime,
                            materType.IsDeleted,
                            materType.CreateUser
                        };

                        var materTypeId = materTypeRepository.QueryFirstOrDefault<long>(sql, parameters);

                        if (materTypeId <= 0)
                        {
                            throw new InvalidOperationException("物料分类创建失败，返回的ID无效");
                        }

                        tran.Complete();

                        result.Code = APIEnums.Success;
                        result.Data = materTypeId;
                        result.Msg = "物料分类创建成功";

                        logger.LogInformation("物料分类 {TypeName} 创建完成，ID: {MaterTypeId}",
                            request.TypeName, materTypeId);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "创建物料分类过程中发生错误: {Message}", ex.Message);
                        result.Code = APIEnums.Error;
                        result.Msg = "创建物料分类失败";
                        result.Data = 0;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "创建物料分类失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "创建物料分类失败";
                result.Data = 0;
            }

            return result;
        }
    }
}